import { NextRequest, NextResponse } from 'next/server';
import ChainMonitorConfigService from '@/services/config/ChainMonitorConfigService';
import { createModuleLogger } from '@/utils/logger';

const logger = createModuleLogger('chain-config-api');

// GET - 获取所有链配置
export async function GET(request: NextRequest) {
  try {
    const configService = ChainMonitorConfigService.getInstance();
    const configs = await configService.getAllChainConfigs();
    
    return NextResponse.json({
      success: true,
      data: configs,
      timestamp: new Date().toISOString()
    });
    
  } catch (error) {
    logger.error('获取链配置失败:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : '获取链配置失败',
      timestamp: new Date().toISOString()
    }, { status: 500 });
  }
}

// POST - 更新链配置
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { chain, config } = body;
    
    if (!chain) {
      return NextResponse.json({
        success: false,
        error: 'Missing chain parameter'
      }, { status: 400 });
    }

    const configService = ChainMonitorConfigService.getInstance();
    const success = await configService.updateChainConfig(chain, config);
    
    if (success) {
      const updatedConfig = await configService.getChainConfig(chain);
      return NextResponse.json({
        success: true,
        message: `${chain} 配置更新成功`,
        data: updatedConfig,
        timestamp: new Date().toISOString()
      });
    } else {
      throw new Error('配置更新失败');
    }
    
  } catch (error) {
    logger.error('更新链配置失败:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : '更新链配置失败',
      timestamp: new Date().toISOString()
    }, { status: 500 });
  }
} 